// 引入类
let Player = require("../modules/Player");
let Game = require("../modules/Game");
let Judge = require("../modules/Judge");
let Event = require("../modules/Event");
let Score = require("../modules/Score");
let Log = require("../modules/Log");

var ObjectID = require("mongodb").ObjectID;
// 处理表单提交
var formidable = require("formidable");
// 引入自定义工具
var zty = require('../public/js/zty');
var excel2json = zty.excel2json;
var resbody = zty.resbody;


// 删除
exports.delete = function(req, res, next) {
  var newResbody = resbody(req);
  try {
    // 得到用户填写的东西
    var form = new formidable.IncomingForm();
    form.encoding = 'utf-8';
    form.parse(req, function(err, fields, files) {

      let target = fields.target;

      switch (target) {
        case "event":
          Event.remove({
            eventId : fields.id
          }, err => {
            if (err) {
              newResbody.status = 500;
              newResbody.msg = '删除' + target + '失败';
              Log.create(newResbody);
              res.json(newResbody);
              return
            }
            newResbody.status = 200;
            newResbody.msg = '删除' + target + '成功！';
            Log.create(newResbody);
            res.json(newResbody);
          });
          break;
        case "game":
          Game.remove({
            gameId : fields.id
          }, err => {
            if (err) {
              newResbody.status = 500;
              newResbody.msg = '删除' + target + '失败';
              Log.create(newResbody);
              res.json(newResbody);
              return
            }
            newResbody.status = 200;
            newResbody.msg = '删除' + target + '成功！';
            Log.create(newResbody);
            res.json(newResbody);
          });
          break;
        case "judge":
          Judge.remove({
            judgeId : fields.id
          }, err => {
            if (err) {
              newResbody.status = 500;
              newResbody.msg = '删除' + target + '失败';
              Log.create(newResbody);
              res.json(newResbody);
              return
            }
            newResbody.status = 200;
            newResbody.msg = '删除' + target + '成功！';
            Log.create(newResbody);
            res.json(newResbody);
          });
          break;
        case "player":
          Player.remove({
            playerId : fields.id
          }, err => {
            if (err) {
              newResbody.status = 500;
              newResbody.msg = '删除' + target + '失败';
              Log.create(newResbody);
              res.json(newResbody);
              return
            }
            newResbody.status = 200;
            newResbody.msg = '删除' + target + '成功！';
            Log.create(newResbody);
            res.json(newResbody);
          });
          break;
        case "score":
          Score.remove(obj);
          break;
      }
    });
  } catch (e) {
    console.log(e);
  }
};



// 处理成绩表
exports.upload = function(req, res, next) {
  var newResbody = resbody(req);
  try {
    if (req.files.apply) {
      excel2json('upload/apply.xlsx', '').then(data => {
        Player.create(data, function(err) {
          if (err && err.code === 11000) {
            newResbody.status = 500;
            newResbody.msg = "数据已经插入过或数据格式有误！";
            Log.create(newResbody);
            console.log(err);
            res.json(newResbody);
            return
          }
          newResbody.status = 200;
          newResbody.msg = '成功插入' +　data.length + '条数据';
          Log.create(newResbody);
          res.json(newResbody);
        });
      });
    } else if (req.files.score) {
      excel2json('upload/score.xlsx', '').then(data => {
        Score.create(data, function(err) {
          if (err && err.code === 11000) {
            newResbody.status = 500;
            newResbody.msg = "数据已经插入过或数据格式有误！";
            Log.create(newResbody);
            console.log(err);
            res.json(newResbody);
            return
          }
          newResbody.status = 200;
          newResbody.msg = '成功插入' +　data.length + '条数据';
          Log.create(newResbody);
          res.json(newResbody);
        });
      });
    } else if (req.files.judge) {
      excel2json('upload/judge.xlsx', '').then(data => {
        Judge.create(data, function(err) {
          if (err && err.code === 11000) {
            newResbody.status = 500;
            newResbody.msg = "数据已经插入过或数据格式有误！";
            Log.create(newResbody);
            console.log(err);
            res.json(newResbody);
            return
          }
          newResbody.status = 200;
          newResbody.msg = '成功插入' +　data.length + '条数据';
          Log.create(newResbody);
          res.json(newResbody);
        });
      });
    }
  } catch (e) {
    console.log(e);
  }
};













// 处理新建运动项目表单
exports.newEvent = function(req, res, next) {
  let newResbody = resbody(req);
  try {
    // 得到用户填写的东西
    var form = new formidable.IncomingForm();
    form.encoding = 'utf-8';
    form.parse(req, function(err, fields, files) {
      let newEvent = {
        "eventId": new Date().getTime(),
        "eventName": fields.eventName,
        "eventType": fields.eventType,
        "fields": fields.fields,
        "eventRecord": fields.eventRecord
        // "admin": req.session.user.id || null  // 管理员 id
      };
      // 创建新比赛
      Event.create(newEvent, function(err) {
        if (err) {
          console.log(err);
          newResbody.status = 500;
          newResbody.msg = "创建新运动项目失败！请稍后重试！";
          Log.create(newResbody);
          res.json(newResbody);
          return
        }
        newResbody.status = 200;
        newResbody.msg = '创建新运动项目：' +　newEvent.eventName + '成功！';
        Log.create(newResbody);
        res.json(newResbody);
      });
    })
  } catch (e) {
    console.log(e);
  }
};

// 处理新建比赛表单
exports.newGame = function(req, res, next) {
  let newResbody = resbody(req);
  try {
    // 得到用户填写的东西
    var form = new formidable.IncomingForm();
    form.encoding = 'utf-8';
    form.parse(req, function(err, fields, files) {
      // 初赛信息
      let gameInfo = fields;

      // 创建新比赛
      Game.create(gameInfo, function(err) {
        if (err) {
          console.log(err);
          newResbody.status = 500;
          newResbody.msg = "比赛：" +　gameInfo.gameName + " 已创建！";
          Log.create(newResbody);
          res.json(newResbody);
          return
        }

        if (gameInfo.game0id) {
          // 表示已安排决赛
          Game.update({gameId: gameInfo.game0id}, {$set: {gameStatus: "3"}}, err => {
            newResbody.status = 200;
            newResbody.msg = '创建新比赛：' +　gameInfo.gameName + ' 成功！';
            Log.create(newResbody);
            res.json(newResbody);
          });
        } else {
          newResbody.status = 200;
          newResbody.msg = '创建新比赛：' +　gameInfo.gameName + ' 成功！';
          Log.create(newResbody);
          res.json(newResbody);
        }
      });
    })
  } catch (e) {
    console.log(e);
  }
};

// 录入运动员得分
exports.enterPlayerMark = function(req, res, next) {
  let newResbody = resbody(req);
  try {
    // 得到用户填写的东西
    var form = new formidable.IncomingForm();
    form.encoding = 'utf-8';
    form.parse(req, function(err, fields, files) {
      let players = fields.players;
      let game1id = fields.gameId;
      players.forEach(e => {
        let gameId = e.gameId;
        let playerId = e.playerId;
        let playerMark = e.playerMark;

        Player.findOne({playerId}, (err, result) => {
          let oldPlayerMark = result.playerMark || 0;
          let newPlayerMark = playerMark + oldPlayerMark;
          Player.update({playerId}, {$set: {playerMark: newPlayerMark}}, function(err) {
            if (err) {
              console.log(err);
              return
            }
          });
        });
      });
      // 表示已录入成绩
      Game.update({gameId: game1id}, {$set: {gameStatus: "4"}}, err => {
        newResbody.status = 200;
        newResbody.msg = '录入得分成功！';
        Log.create(newResbody);
        res.json(newResbody);
      });
    })
  } catch (e) {
    console.log(e);
  }
};


// 用户登录
exports.signIn = function(req, res, next) {
  let newResbody = resbody(req);
  try {
    // 得到用户填写的东西
    var form = new formidable.IncomingForm();
    form.encoding = 'utf-8';
    form.parse(req, function(err, fields, files) {

      req.session.login = true;
      req.session.userId = fields.userId;
      req.session.userType = fields.userType;

      newResbody.status = 200;
      newResbody.msg = '登录成功！';
      Log.create(newResbody);
      res.json(newResbody);
    })
  } catch (e) {
    console.log(e);
  }
};


// 退出登录
exports.signOut = function(req, res, next) {
  try {
    req.session.login = false;
    req.session.userId = "";
    req.session.userType = "";

    res.redirect("/");
  } catch (e) {
    console.log(e);
  }
};
























// 格式化输出日期
Date.prototype.Format = function(fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};
